//
//  XMRefreshControl.swift
//  XMWeibo-Swift
//
//  Created by 育鑫 王 on 15/11/3.
//  Copyright © 2015年 育鑫 王. All rights reserved.
//

import UIKit

class XMRefreshControl: UIRefreshControl {

    // MARK: - 属性
    // 箭头旋转的值
    private let RefreshControlOffset : CGFloat = -60
    
    // 标记, 用于去除重复答应
    private var isUp = false
    
    /// 覆盖父类的frame属性
    override var frame: CGRect {
        didSet {
//            print("frame\(frame)第几次")
            if frame.origin.y >= 0 {
                return
            }
            
            // 开始旋转
            if refreshing {
            refreshView.startLoading()
            }
        
            if frame.origin.y < RefreshControlOffset && isUp {
                print("箭头转上去")
                isUp = !isUp
                refreshView.rotationTipViewIcon(isUp)
            }else if frame.origin.y > RefreshControlOffset && !isUp {
                print("箭头转下去")
                isUp = !isUp
                refreshView.rotationTipViewIcon(isUp)
            }
            
        }
    }
    // 重写endRefreshing
    override func endRefreshing() {
        super.endRefreshing()
        
        refreshView.stopLoading()
    }
    
    // MARK: - 构造函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
//    override init(frame: CGRect) {
//        super.init(frame: frame)
//        
//        prepareUI()
//    }
    override init() {
        super.init()
        prepareUI()
    }
    // 准备UI
    func prepareUI() {
        // 添加子控件
        addSubview(refreshView)
        
        // 添加约束
        refreshView.ff_AlignInner(type: ff_AlignType.CenterCenter, referView: self, size: refreshView.bounds.size)
    }

    // MARK: - 懒加载
    // 自定的刷新view
    private lazy var refreshView: XMRefreshView = XMRefreshView.refreshView()
}

// 自定义刷新的view
class XMRefreshView: UIView {
    
    @IBOutlet weak var loadingView: UIImageView!
    // 加载xib
    @IBOutlet weak var tipViewIcon: UIImageView!
    
    @IBOutlet weak var tipView: UIView!
    
    // 加载xib
    class func refreshView() -> XMRefreshView {
        return NSBundle.mainBundle().loadNibNamed("XMRefreshView", owner: self, options: nil).last as! XMRefreshView
    }
    
    /**
    箭头旋转动画
    
    - parameter ture：向上 false：向下
    */
    func rotationTipViewIcon(isup: Bool) {
        UIView.animateWithDuration(0.25) { () -> Void in
            self.tipViewIcon.transform = isup ? CGAffineTransformMakeRotation(CGFloat(M_PI - 0.01)) : CGAffineTransformIdentity
        }
    }
    
    /// 开始旋转
    func startLoading() {
        // 如果动画正在执行, 不添加动画
        let animKey = "animKey"
        // 获取图层上所有正在执行的动画的key
        if let _ = loadingView.layer.animationForKey(animKey) {
            // 找到对应的动画,动画正在执行,直接返回
            return
        }
        tipView.hidden = true
        
        // 旋转
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.repeatCount = MAXFLOAT
        anim.duration = 0.25
        anim.toValue = M_PI * 2
        
        anim.removedOnCompletion = false
        
        // 开始动画, 名称一样会先停止正在执行的动画,重新添加
        loadingView.layer.addAnimation(anim, forKey: animKey)
    }
    
    /// 停止旋转
    func stopLoading() {
        // 显示tipView
        tipView.hidden = false
        
        // 停止旋转
        loadingView.layer.removeAllAnimations()
    }
}
